import { app, BrowserWindow, ipcMain, dialog, Tray, nativeImage, Menu, clipboard, systemPreferences, globalShortcut, session } from 'electron'
import { initDatabase, closeDatabase, createTableMessage, getMessagesByPage, searchWholeMessagesLike, insertMessage } from './database/index'
import path, { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import logger from './utils/logger'
import $config from '../config/index.json'
import { ref } from 'vue'
import { createFilePackage, writeFile } from './utils/file'
import fs from 'fs'
import child_process from 'child_process'
import Shortcut from './utils/shortcut'
// import { checkForUpdates } from './utils/auto-update'
import { config } from 'dotenv'
const mode = process.env.MODE
console.log('mode', mode)
config({ path: ['.env', `.env.${mode}`]})
const __dirname = path.dirname(fileURLToPath(import.meta.url))



const indexHtml = path.join(__dirname, '../index.html')
const preload = path.join(__dirname, 'preload.js')

// 系统平台
let system = process.platform

let win: BrowserWindow | undefined
// 解决控制台警告
process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true'

//创建登录窗口
let loginWindow: BrowserWindow | null
async function createLoginWindow() {
  loginWindow = new BrowserWindow({
    width: 300, // 窗口宽度
    height: 300, // 窗口高度
    frame: false,
    autoHideMenuBar: true,
    webPreferences: {
      sandbox: false,
      preload: preload,
      nodeIntegration: true,
      contextIsolation: true,
      webSecurity: true //允许跨域
    }
  })
  // 窗口最大化
  loginWindow.maximize()
  loginWindow.webContents.openDevTools()
  if (process.env.VITE_DEV_SERVER_URL) {
    loginWindow.loadURL(process.env.VITE_DEV_SERVER_URL)
    await session.defaultSession.loadExtension(join(process.cwd(), 'Vue Devtools'))
  } else {
    loginWindow.loadFile(indexHtml)
    await session.defaultSession.loadExtension(join(process.cwd(), 'Vue Devtools'))
  }

  // 页面加载完成再显示
  // loginWindow.once('ready-to-show', () => {
  //   loginWindow?.show()
  //   if (app.isPackaged) {
  //     checkForUpdates()
  //   }
  // })

  ipcMain.once('already-login', () => {
    console.log('already-login')
    loginWindow?.hide()
    if (!win) {
      createWindow()
    }
  })
  ipcMain.once('need-login', () => {
    console.log('need-login')
    loginWindow?.show()
  })
  ipcMain.once('login-success', () => {
    loginWindow?.hide()
    if (!win) {
      createWindow()
    }
  })
}

// 创建主进程窗口
function createWindow() {
  // 创建主窗口
  win = new BrowserWindow({
    title: $config.title,
    width: 1000,
    height: 700,
    frame: false,
    // icon: path.join(process.env.PUBLIC, 'electron-vite.svg'),
    autoHideMenuBar: true, // 隐藏默认菜单
    webPreferences: {
      sandbox: false,
      preload: preload,
      nodeIntegration: true,
      contextIsolation: false,
      webviewTag: true, //允许使用 webview
      webSecurity: false //允许跨域
    }
  })
  // 窗口最大化
  win.maximize()
  win.setMenu(null)
  // 打开控制台
  win.webContents.openDevTools()
  // Test active push message to Renderer-process.
  win.webContents.on('did-finish-load', () => {
    win?.webContents.send('main-process-message', new Date().toLocaleString())
    if (loginWindow) {
      loginWindow.close()
    }
  })
  if (process.env.VITE_DEV_SERVER_URL) {
    win.loadURL(process.env.VITE_DEV_SERVER_URL)
  } else {
    // win.loadFile('dist/index.html')
    win.loadFile(indexHtml)
  }

  // 关闭登录窗口
  // loginWindow?.close()

  const icon = nativeImage.createFromPath(path.join(process.env.PUBLIC, 'release.png'))
  let tray = new Tray(icon)
  const contextMenu = Menu.buildFromTemplate([
    { label: 'Item1', type: 'radio' },
    { label: 'Item2', type: 'radio' },
    { label: 'Item3', type: 'radio', checked: true },
    { label: 'Item4', type: 'radio' }
  ])
  tray.setToolTip('This is my application.')
  tray.setContextMenu(contextMenu)
  tray.on('click', () => {
    win?.show()
  })
  // 窗口关闭
  win.on('close', e => {
    e.preventDefault()
    // 窗口关闭提示弹框
    win &&
      dialog
        .showMessageBox(win, {
          type: 'info',
          title: '提示',
          message: '请确认是否关闭？',
          buttons: ['确认', '取消'],
          cancelId: 1
        })
        .then(idx => {
          if (idx.response != 1) {
            // 关闭所有数据库连接
            // closeDatabase()
            app.exit()
          }
        })
  })
  let timer = ref()

  ipcMain.on('message', (_, message) => {
    if (message === 'start') {
      if (timer.value) return
      tray.setImage(path.join(process.env.PUBLIC, 'release_transparent.png'))
      let count = 0
      timer.value = setInterval(() => {
        count++
        if (count % 2 == 0) {
          tray.setImage(path.join(process.env.PUBLIC, 'release_transparent.png'))
        } else {
          tray.setImage(path.join(process.env.PUBLIC, 'release.png'))
        }
      }, 500)
    } else {
      clearInterval(timer.value)
      timer.value = null
      tray.setImage(path.join(process.env.PUBLIC, 'release.png'))
    }
  })

  ipcMain.on('call-response', (_, _type) => {
    // callReminder?.close()
  })

  // ipcMain.on('download-file', (_, fileName, arrayBuffer, id, key) => {
  //   writeFile(fileName, arrayBuffer, id, key)
  // })

  // ipcMain.on('search-msg', (_, page, pageSize, chatId) => {
  //   getMessagesByPage(page, pageSize, chatId).then(res => {
  //     win?.webContents.send('search-msg-result', res)
  //   })
  // })

  ipcMain.on('show-home-context-menu', () => {
    // 创建自定义菜单
    const menu = Menu.buildFromTemplate([
      { label: '自定义项1', click: () => console.log('自定义项1被点击') },
      { label: '自定义项2', click: () => console.log('自定义项2被点击') },
      { type: 'separator' }, // 分隔线
      { label: '自定义项3', click: () => console.log('自定义项3被点击') }
    ])

    // 将自定义菜单显示在鼠标位置\work\study\vue-admin-electron\dist\electron\preload.js
    menu.popup()
  })

  ipcMain.on('show-context-menu', (_, msgType, message, filePath) => {
    // console.log('show-context-menu', msgType, message, filePath)
    let menu
    menu = Menu.buildFromTemplate([
      {
        label: '复制',
        click: () => {
          // 剪贴板
          if (msgType === 'text') {
            clipboard.writeText(message)
          } else {
            const fileUrl = filePath.replace('/', '')
            fs.readFile(fileUrl, 'base64', function (err, result) {
              //打印成功结果,如果读取失败
              if (err) {
                return console.log('文件读取失败' + err.message)
              }
              // 写入剪贴板
              clipboard.writeHTML(`<img src="data:image/png;base64,${result}" style="width: 60px;height: 60px;object-fit: cover;"/>`)
              // win?.webContents.send('image-to-clipboard', `data:image/png;base64,${result}`)
            })
          }
        }
      }
    ])

    // 将自定义菜单显示在鼠标位置
    menu.popup()
  })

  // ipcMain.on('fuzzy-query', (_, searchText) => {
  //   searchWholeMessagesLike(searchText).then(res => {
  //     win?.webContents.send('fuzzy-query-result', res)
  //   })
  // })

  // ipcMain.on('insert-msg', (_, msg) => {
  //   insertMessage(JSON.parse(msg))
  // })

  ipcMain.on('notification-click', () => {
    win?.show()
  })

  ipcMain.on('minimize', () => {
    win?.minimize()
  })

  ipcMain.on('maximize', () => {
    win?.maximize()
  })

  ipcMain.on('restore', () => {
    win?.unmaximize()
  })

  ipcMain.on('close', () => {
    win?.close()
  })

  let previewWindow: BrowserWindow | null
  ipcMain.on('show-preview', () => {
    previewWindow = new BrowserWindow({
      frame: false, // 无边框
      transparent: true, // 透明背景
      webPreferences: {
        sandbox: false,
        preload: preload,
        nodeIntegration: true,
        contextIsolation: false,
        webSecurity: false //允许跨域
      }
    })
    if (process.env.VITE_DEV_SERVER_URL) {
      previewWindow.loadURL(`${process.env.VITE_DEV_SERVER_URL}/preview`)
    } else {
      // callReminder.loadURL(path.join(`file://${__dirname}/index.html`, '/#/callReminder'))
      previewWindow.loadFile(indexHtml, { hash: '/preview' })
    }
  })

  ipcMain.on('close-preview', () => {
    previewWindow?.close()
  })

  let child: BrowserWindow | undefined
  ipcMain.on('add-participant', () => {
    child = new BrowserWindow({
      width: 800, // 窗口宽度
      height: 600, // 窗口高度
      webPreferences: {
        preload: path.join(__dirname, 'preload.mjs'),
        nodeIntegration: true,
        contextIsolation: false,
        webSecurity: false //允许跨域
      },
      parent: win,
      modal: true
    })
    // child.loadURL(`${VITE_DEV_SERVER_URL}/#/tree`)
    if (process.env.VITE_DEV_SERVER_URL) {
      child.loadURL(`${process.env.VITE_DEV_SERVER_URL}/tree`)
    } else {
      // win.loadFile('dist/index.html')
      // child.loadURL(path.join(process.env.DIST, 'index.html/#/tree'))
      child.loadFile(indexHtml, { hash: '/tree' })
    }
    child.once('ready-to-show', () => {
      child?.show()
    })
  })

  ipcMain.on('add-member', (_, member) => {
    child?.close()
    win?.webContents.send('add-member-result', member)
  })

  ipcMain.on('cancel-add-member', () => {
    child?.close()
  })

  ipcMain.on('inspect-equipment', () => {
    checkAndApplyDeviceAccessPrivilege()
  })

  // 启动截图工具
  startScreenShot()
}

// 检查并获取设备权限
async function checkAndApplyDeviceAccessPrivilege() {
  // 检查并获取摄像头权限
  const cameraPrivilege = systemPreferences.getMediaAccessStatus('camera')
  console.log(`Camera privilege before applying: ${cameraPrivilege}`)
  if (cameraPrivilege !== 'granted') {
    await systemPreferences.askForMediaAccess('camera').catch(err => {
      console.log(err)
    })
    console.log('Requested camera access from user')
  }

  // 检查并获取麦克风权限
  const micPrivilege = systemPreferences.getMediaAccessStatus('microphone')
  console.log(`Microphone privilege before applying: ${micPrivilege}`)
  if (micPrivilege !== 'granted') {
    await systemPreferences.askForMediaAccess('microphone').catch(err => {
      console.log(err)
    })
    console.log('Requested microphone access from user')
  }
}

// 启动截图工具
const startScreenShot = () => {
  if (system === 'win32') {
    // var screen_window = execFile(path.join(app.getPath("userData"), "/capture/Snipaste.exe"))
    var screen_window = child_process.execFile(path.join(__dirname, '../src/capture/Snipaste.exe'))
    screen_window.on('exit', function (_code) {
      // 执行成功返回 1，返回 0 没有截图
      // console.log('222', code)
    })
  } else if (system === 'darwin') {
    child_process.exec(`screencapture -i -c`, (error, stdout, _stderr) => {
      console.log('308', error)
      if (!error) {
        //截图完成，在粘贴板中
        console.log('screenshot success', stdout)
      }
    })
  }
}

// 当所有的窗口都被关闭时触发
app.on('window-all-closed', () => {
  // win = null
  app.quit()
})

// 主进程和渲染进程通信
// 日志记录
type LoggerLevel = 'info' | 'warn' | 'error' | 'debug' | 'verbose' | 'silly'
ipcMain.handle('logger', (_event, level: LoggerLevel, content: string) => {
  logger[level](content)
})

// 当Electron 初始化完成
app.whenReady().then(() => {
  // 初始化数据库
  // initDatabase()
  // // 创建消息表
  // createTableMessage()
  // // 创建文件夹储存文件
  // createFilePackage()
  // 删除历史日志
  // deleteHistoryLog()
  // 根据是否登录创建对应窗口
  createLoginWindow()
})

//监听失去焦点事件,注销快捷键
app.on('browser-window-blur', () => {
  globalShortcut.unregisterAll()
})

//监听获得焦点事件,注册快捷键
app.on('browser-window-focus', () => {
  Shortcut()
})
